package org.bangumibuddy.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.SneakyThrows;
import org.bangumibuddy.constant.Constant;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    public static String createJWT(String secreKey, Long ttlMills, Map<String, String> Claim) {
        Date expireData = new Date(System.currentTimeMillis() + ttlMills);
        Algorithm algorithm = Algorithm.HMAC256(secreKey);


        return JWT.create()
                .withClaim(Constant.CLAIM, Claim)
                .withExpiresAt(expireData)
                .sign(algorithm);
    }

    @SneakyThrows
    public static String getProperty(String propertyName, String token, String secretKey) {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
        Map<String, Object> map = decodedJWT.getClaim(Constant.CLAIM).asMap();

        return (String) map.get(propertyName);
    }

    @SneakyThrows
    public static boolean verityToken(String token, String secretKey) {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        JWT.require(algorithm).build().verify(token);

        return true;
    }

    @SneakyThrows
    public static Map<String,Object> getClaim(String token, String secretKey) {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
        return decodedJWT.getClaim(Constant.CLAIM).asMap();
    }
}
